package com.wql.crypto;

import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import com.wql.crypto.common.HexUtils;

/**
 * 加解密工具类
 * 
 * @author wuqinglong
 * @time 2013年11月6日 下午3:05:55
 * @email hellowql@126.com
 */
public class MACUtils {
	private MACUtils() {
	}

	// private static final String KEY_ALGORITHM = "HmacMD5";// 128

	private static final String KEY_ALGORITHM = "HmacSHA1";// 160

	// private static final String KEY_ALGORITHM = "HmacSHA256";
	// private static final String KEY_ALGORITHM = "HmacSHA384";
	// private static final String KEY_ALGORITHM = "HmacSHA512";

	private static final String PASSWORD = "3232E6B8EEFC8EC59194195FC1C92D3D";

	private static final String CIPERH_ALGORITHM = KEY_ALGORITHM;

	private static final String CHARSE_TNAME = "utf-8";

	/**
	 * 生成密钥
	 * 
	 * @return
	 */
	public static String initKey() {
		return initKey(128, null);
	}

	/**
	 * 生成密钥
	 * 
	 * @param length
	 * @return
	 */
	public static String initKey(int length, String seed) {
		KeyGenerator kg;
		try {
			kg = KeyGenerator.getInstance(KEY_ALGORITHM);
			if (null != seed)
				kg.init(length, new SecureRandom(seed.getBytes()));
			else
				kg.init(length);
			SecretKey key = kg.generateKey();
			return HexUtils.byte2HexStr(key.getEncoded());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 密钥转换
	 * 
	 * @param keyArr
	 * @return
	 */
	public static Key toKey(String key) {
		SecretKey secretKey = new SecretKeySpec(HexUtils.hexStr2byte(key), KEY_ALGORITHM);
		return secretKey;
	}

	/**
	 * 加密
	 * 
	 * @param data
	 * @return
	 */
	public static String encrypt(String data) {
		return encrypt(data, PASSWORD);
	}

	/**
	 * 加密
	 * 
	 * @param data
	 * @param key
	 * @return
	 */
	public static String encrypt(String data, String key) {
		try {
			Mac cipher = Mac.getInstance(CIPERH_ALGORITHM);// 创建密码器
			cipher.init(toKey(key));// 初始化
			byte[] result = cipher.doFinal(data.getBytes(CHARSE_TNAME));
			return HexUtils.byte2HexStr(result); // 加密
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) throws Exception {
		String msgString = "1ABABABABABA";
		System.out.println(encrypt(msgString));
		System.out.println(encrypt(msgString).length());
	}
}
